package com.chuangyi.config.server.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by fangtao on 2017/6/4.
 */
@Configuration
public class ZookeeperConfig {

    @Value("${zookeeper.hosts}")
    private String hosts;

    @Value("${zookeeper.retry.times}")
    private int retryTimes;

    @Value("${zookeeper.retry.interval}")
    private int retryInterval;

    @Value("${zookeeper.leader.path}")
    private String masterPath;


    @Bean(initMethod = "start")
    public CuratorFramework curatorFramework() {
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(hosts, retryPolicy());
        return curatorFramework;
    }

    @Bean
    public RetryPolicy retryPolicy() {
        return new RetryNTimes(retryTimes, retryInterval);
    }

    @Bean(initMethod = "start")
    public LeaderSelector leaderSelector() throws Exception {
        LeaderSelector leaderSelector = new LeaderSelector(curatorFramework(), masterPath, new LeaderSelectorListenerAdapter() {
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                client.create().forPath("/path", new byte[2]);
            }
        });
        leaderSelector.autoRequeue();
        return leaderSelector;
    }


}
